//
//  MinePageOpusListViewController.m
//  ShowYork
//
//  Created by hxh on 2021/3/5.
//  Copyright © 2021 hxh. All rights reserved.
//

#import "MinePageOpusListViewController.h"
#import "HomePageDetailViewController.h"
#import "MineCreateOpusViewController.h"
#import "SLEditVideoController.h"
#import "WaterFallLayout.h"
#import "MinePageOpusListCell.h"

#import "ZLPhotoBrowser-Swift.h"
#import "SocialReleaseModel.h"


@interface MinePageOpusListViewController ()<WaterFallLayoutDelegate,UICollectionViewDelegate,UICollectionViewDataSource,MinePageOpusListCellDelegate>
@property (nonatomic,strong)UICollectionView *collectionView;
@property (nonatomic,strong)UIView *noDataView;
@property (nonatomic,strong)UIImageView *noDataImgView;
@property (nonatomic,strong)UILabel *noDateLb;
@property (nonatomic,strong)NSMutableArray *dataArray;

@property (nonatomic,assign)NSInteger page;

@property (nonatomic,strong)UIView *navView;
@property (nonatomic,strong)UILabel *navCountLb;
@property (nonatomic,strong)UILabel *navTitleLb;

@property (nonatomic,assign)CGFloat total;

@property (nonatomic,strong)UIView *refreshView;

@end

@implementation MinePageOpusListViewController

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
   
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    blackLineImageView.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    blackLineImageView.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    [self showDataLoadState];
    [self loadDataSource];
    [self registNote];
}
- (void)setUI{
    
    
    [MobClick event:@"mine_work_show"];
    
    self.page = 1;
    
    self.navView = [[UIView alloc]init];
    self.navTitleLb = [[UILabel alloc]init];
    self.navTitleLb.text = @"我的作品";
    self.navTitleLb.textColor = RGBA(35, 24, 21, 1);
    self.navTitleLb.font = [UIFont boldSystemFontOfSize:18];
    [self.navView addSubview:self.navTitleLb];
    
    self.navCountLb = [[UILabel alloc]init];
    self.navCountLb.textColor = RGBA(35, 24, 21, 1);
    self.navCountLb.font = font(12);
    [self.navView addSubview:self.navCountLb];
    
    [self.navTitleLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.navView);
    }];
    [self.navCountLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.navTitleLb);
        make.left.equalTo(self.navTitleLb.mas_right).offset(2);
    }];
    
    self.navigationItem.titleView = self.navView;
    
    
    UIButton *btn = [[UIButton alloc]init];
    [btn setTitle:@"创作投稿" forState:UIControlStateNormal];
    [btn setTitleColor:C102 forState:UIControlStateNormal];
    btn.titleLabel.font = font(12);
    [btn addTarget:self action:@selector(createMethod) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:btn];
    
    WaterFallLayout *layout = [[WaterFallLayout alloc]init];
    layout.delegate = self;
    layout.minimumLineSpacing = 5.0f;
    layout.minimumInteritemSpacing = 5.0f;
    layout.sectionInset = UIEdgeInsetsMake(0, 5, 0, 5);

    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.collectionView];
    
    [self.collectionView registerClass:[MinePageOpusListCell class] forCellWithReuseIdentifier:@"MinePageOpusListCell"];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
    

    self.collectionView.backgroundColor = [UIColor whiteColor];
    __weak typeof(self)weakSelf = self;
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page = 1;
        [weakSelf loadDataSource];
    }];
    self.collectionView.mj_header = header;
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.page++;
        [weakSelf loadDataSource];
        
    }];
    [footer setTitle:@"—— 没有更多了 ——" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = font(10);
    footer.stateLabel.textColor = RGBA(153, 153, 153, 1);
    footer.hidden = YES;
    self.collectionView.mj_footer = footer;
    
    self.noDataView = [[UIView alloc]init];
    self.noDataView.backgroundColor = [UIColor whiteColor];
    self.noDataView.hidden = YES;
    [self.view addSubview:self.noDataView];
    
    [self.noDataView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
   
    self.noDataImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"mine_noList_tag"]];
    [self.noDataView addSubview:self.noDataImgView];
    
    [self.noDataImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.view).offset(-kNavBarHeight);
        make.centerX.equalTo(self.view);
    }];
    
    self.noDateLb = [[UILabel alloc]init];
    self.noDateLb.text = @"空空如也，快去发上传作品吧～";
    self.noDateLb.textColor = C153;
    self.noDateLb.font = font(12);
    self.noDateLb.textAlignment = NSTextAlignmentCenter;
    [self.noDataView addSubview:self.noDateLb];
    [self.noDateLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.noDataView);
        make.top.equalTo(self.noDataImgView.mas_bottom).offset(12);
    }];
    

    
    UIView *v2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
    v2.backgroundColor = RGBA(248, 248, 248, 1);
    
    UIView *v3 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 120)];
    v3.backgroundColor = [UIColor whiteColor];
    
    self.refreshView = v3;
    
    [v2 addSubview:v3];

    v2.layer.zPosition = -2;
    self.collectionView.backgroundView = v2;
    

    UIView *v = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 120)];
    v.layer.zPosition = -1;
    v.userInteractionEnabled = NO;
    CAGradientLayer *leftLayer = [CAGradientLayer layer];
    leftLayer.frame = v.bounds;
    leftLayer.colors = @[(id)RGBA(255, 255, 255, 1).CGColor,(id)RGBA(248, 248, 248, 1).CGColor];
    [v.layer addSublayer:leftLayer];
    
    
    [self.collectionView insertSubview:v atIndex:0];
    self.collectionView.backgroundColor = RGBA(248, 248, 248, 1);
   
}

- (void)createMethod{
    [MobClick event:@"mine_work_add_click"];
    [self addVideo];
}

- (void)loadDataSource{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"postId"] = [RPAppManager getCustomerId];
    param[@"pageIndex"] = @(self.page);
    param[@"pageSize"] = @(10);
    param[@"type"] = @"2";
    param[@"md5"] = [RPAppManager md5StrWithApi:GetUserPostList];
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(GetUserPostList) parames:param success:^(id responseObj) {
        
        [self hideDataLoadLoadState];
        
        if ([self.collectionView.mj_header isRefreshing]) {
            [self.collectionView.mj_header endRefreshing];
        }
        if ([self.collectionView.mj_footer isRefreshing]) {
            [self.collectionView.mj_footer endRefreshing];
        }
        CGFloat bottom = self.collectionView.mj_insetB;
        if ([responseObj[RESPONSE][LASTPAGE]boolValue]) {
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
            if (self.collectionView.mj_footer.cl_height == 44.0f) {
                self.collectionView.mj_footer.cl_height = 138.0f;
                if (bottom == 44.0f || bottom == GK_SAVEAREA_BTM + 44.0f) {
                    self.collectionView.mj_insetB = 138.0f;
                }
            }
        }else{
            [self.collectionView.mj_footer resetNoMoreData];
            if (self.collectionView.mj_footer.cl_height == 138.0f) {
                self.collectionView.mj_footer.cl_height = 44.0f;
                if (bottom == 138.0f) {
                    self.collectionView.mj_insetB = 44.0f;
                }
            }
            
        }
        if (self.page == 1) {
            self.dataArray = [HomePageItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]];
        }else{
            [self.dataArray addObjectsFromArray:[HomePageItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]]];
        }
        self.total = [responseObj[RESPONSE][TOTAL] floatValue];
        NSString *title = @"";
        if (self.total >= 10000) {
            NSInteger count = self.total;
            if (count % 1000 == 0) {
                count += 1;
            }
            title = [NSString stringWithFormat:@"(%@w)",[RPAppManager notRounding:count/10000.0f afterPoint:1]];
        }else{
            title = [NSString stringWithFormat:@"(%i)",(int)self.total];
        }
        self.navCountLb.text = title;
        self.collectionView.mj_footer.hidden = self.dataArray.count == 0;
        self.noDataView.hidden = self.dataArray.count > 0;
        [self.collectionView reloadData];
    } failure:^(id error) {
        [self hideDataLoadLoadState];
        if ([self.collectionView.mj_header isRefreshing]) {
            [self.collectionView.mj_header endRefreshing];
        }

        if ([self.collectionView.mj_footer isRefreshing]) {
            [self.collectionView.mj_footer endRefreshing];
        }
    }];
}

- (void)registNote{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateListSource) name:@"updateUserInfoOpusList" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteHomePageItem:) name:@"deleteHomePageItem" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateVideoItem:) name:@"updateReleaseVideo" object:nil];
}

- (void)updateVideoItem:(NSNotification *)note{
    NSString *videoPath = note.userInfo[@"data"];
    
    if (![note.userInfo[@"stauts"] boolValue]) {
        return;
    }
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:videoPath] options:nil];
    AVAssetImageGenerator *assetGen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetGen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [assetGen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *videoImage = [[UIImage alloc] initWithCGImage:image];
    CGImageRelease(image);
    
    SocialReleaseModel *itemModel = [[SocialReleaseModel alloc]init];
    itemModel.isVideo = YES;
    itemModel.videoUrl = videoPath;
    itemModel.image = videoImage;
    dispatch_async(dispatch_get_main_queue(), ^{
        MineCreateOpusViewController *createVC = [[MineCreateOpusViewController alloc]initWithPostItem:itemModel];
        [self.navigationController pushViewController:createVC animated:YES];
    });
}

- (void)deleteHomePageItem:(NSNotification *)note{
    HomePageItemModel *item = note.userInfo[@"data"];
    __block NSInteger index = -1;
    [self.dataArray enumerateObjectsUsingBlock:^(HomePageItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if([obj.postId isEqualToNumber:item.postId]){
            index = idx;
            *stop = YES;
        }
    }];
    if (index != -1) {
        NSString *title = @"";
        self.total--;
        if (self.total >= 10000) {
            NSInteger count = self.total;
            if (count % 1000 == 0) {
                count += 1;
            }
            title = [NSString stringWithFormat:@"(%@w)",[RPAppManager notRounding:count/10000.0f afterPoint:1]];
        }else{
            title = [NSString stringWithFormat:@"(%i)",(int)self.total];
        }
        self.navCountLb.text = title;
        
        [self.dataArray removeObjectAtIndex:index];
        
        if (self.dataArray.count == 0 && self.total != 0) {
            self.page++;
            [self loadDataSource];
        }else{
            if (self.dataArray.count != self.total) {
                [self.collectionView.mj_footer resetNoMoreData];
            }
            [self.collectionView reloadData];
        }
    }
}

- (void)updateListSource{
    self.page = 1;
    [self showDataLoadState];
    [self loadDataSource];
}

- (CGFloat)flowLayout:(UICollectionViewLayout *)layout heightForIndexPath:(NSIndexPath *)indexPath{
    
    HomePageItemModel *itemModel = self.dataArray[indexPath.item];
    
    CGFloat screenW = UIScreen.mainScreen.bounds.size.width;
    // 计算一半的宽度占比
    CGFloat itemW = (screenW - 3 * 5)/2;
    // 计算图片的高度3/4
    CGFloat imgH = itemW/3*4;
    
    CGSize textSize = [self getTextSizeWithText:itemModel.contentText font:[UIFont systemFontOfSize:12] maxSize:CGSizeMake(itemW - 16, MAXFLOAT)];
    
    if (itemModel.contentType.intValue == 1) {
        return imgH + 40;
    }else{
        if (itemModel.contentText.length == 0) {
            return imgH + 38;
        }else{
            CGFloat maxH = [self heightOfLines:2 font:[UIFont systemFontOfSize:12]];
            return imgH + MIN(ceil(textSize.height),maxH) + 12 + 34;
        }
    }
}
- (CGFloat)heightOfLines:(int)lines font:(UIFont *)font{
    if (lines <= 0) {
        return 0;
    }
    NSString *str = @"*";
    for (int index = 0; index < lines - 1 ; index++) {
        str = [str stringByAppendingString:@"\n*"];
    }
    NSDictionary *dict = @{NSFontAttributeName:font};
    
    CGSize size = [str sizeWithAttributes:dict];
    
    return ceil(size.height);
}

- (CGSize)getTextSizeWithText:(NSString *)text font:(UIFont *)font maxSize:(CGSize)maxSize
{
    CGSize size = CGSizeZero;
    if(text == nil){
        text = @"";
    }
    if(font == nil){
        font = [UIFont systemFontOfSize:13];
    }
    NSDictionary *attribute = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,nil];
    size = [text boundingRectWithSize:maxSize options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
    return size;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    self.noDataView.hidden = self.dataArray.count > 0;
    self.collectionView.mj_footer.hidden = self.dataArray.count == 0;
    return self.dataArray.count;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MinePageOpusListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MinePageOpusListCell" forIndexPath:indexPath];
    [cell setItemModel:self.dataArray[indexPath.item]];
    cell.delegate = self;
    return cell;
}


- (void)showOpusDetailWithCurrentModel:(HomePageItemModel *)itemModel{
    
    NSInteger index = [self.dataArray indexOfObject:itemModel];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[kXHItemType] = @(XHPageDetailItemTypeMix);
    param[kXHPlatformType] = @(XHPageDetailPlatformTypeMineList);
    param[kXHShowUserInfo] = @(NO);
    param[kXHCurrentPage] = @(self.page);
    param[kXHCurrentIndex] = @(index);
    param[kXHListSource] = self.dataArray;
    param[kXHUserCreateTime] = @(YES);
    HomePageDetailViewController *detailVC = [[HomePageDetailViewController alloc]initWithConfigInfo:param];
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}


- (void)addVideo{

    if (![RPAppManager checkVideoPhotoAuthorization]) {
        [self setAuthStatusWithMessage:@"此功能需要您授权本App打开照片\n设置方法: 打开手机设置->隐私->照片"];
        return;
    }
    [ZLPhotoConfiguration default].maxSelectCount = 1;
    [ZLPhotoConfiguration default].allowSelectVideo = true;
    [ZLPhotoConfiguration default].showSelectBtnWhenSingleSelect = false;
    [ZLPhotoConfiguration default].maxSelectVideoDuration = 3600;
    [ZLPhotoConfiguration default].allowSelectImage = false;
    [ZLPhotoConfiguration default].allowMixSelect = false;
    [ZLPhotoConfiguration default].allowEditImage = false;
    [ZLPhotoConfiguration default].allowSelectOriginal = false;
    [ZLPhotoConfiguration default].allowTakePhoto = false;
    [ZLPhotoConfiguration default].allowRecordVideo = false;
    [ZLPhotoConfiguration default].enablePhotoClip = false;
    [ZLPhotoConfiguration default].allowPreviewVideo = true;
    [ZLPhotoConfiguration default].themeColorDeploy.navEmbedTitleViewBgColor = [UIColor clearColor];
    [ZLPhotoConfiguration default].customImageNames = @[@"zl_retake",@"zl_albumSelect",@"zl_downArrow",@"zl_btn_selected",@"zl_btn_unselected",@"zl_video"];
    [ZLPhotoConfiguration default].bottomToolViewBtnBgImageShow = YES;
    [ZLPhotoConfiguration default].botomToolViewBtnBgImageName = @"social_confirm_tag";
    [ZLPhotoConfiguration default].themeColorDeploy.bottomToolViewBtnNormalBgColor = RGBA(245, 75, 100, 1);
    [ZLPhotoConfiguration default].navTitleFont = [UIFont boldSystemFontOfSize:16];
    [ZLPhotoConfiguration default].customLanguageKeyValue_objc = @{@"ok":@"我知道了",@"done":@"完成"};
    [ZLPhotoConfiguration default].showInvalidMask = true;
    [ZLPhotoConfiguration default].enableInvalidClickStatus = true;
    [ZLPhotoConfiguration default].enableBottomToolViewCropView = true;
    [ZLPhotoConfiguration default].languageType = ZLLanguageTypeChineseSimplified;
    [ZLPhotoConfiguration default].themeColorDeploy.bottomToolViewBgColor = RGBA(21, 24, 35, 1);
    [ZLPhotoConfiguration default].themeColorDeploy.navBarColor = RGBA(21, 24, 35, 1);
    [ZLPhotoConfiguration default].themeColorDeploy.albumListBgColor = RGBA(29, 31, 43, 1);
    [ZLPhotoConfiguration default].themeColorDeploy.thumbnailBgColor = RGBA(29, 31, 43, 1);
    [ZLPhotoConfiguration default].videoExportType = VideoExportTypeMp4;
    [ZLPhotoConfiguration default].showVideoHud = true;

    ZLPhotoPreviewSheet *sheet = [[ZLPhotoPreviewSheet alloc]initWithSelectedAssets:@[]];
    
    [ZLPhotoConfiguration default].previewVideoBlock = ^(NSURL * url, UIViewController * viewController) {
        dispatch_async(dispatch_get_main_queue(), ^{
            SLEditVideoController * editViewController = [[SLEditVideoController alloc] init];
            editViewController.videoPath = url;
            editViewController.isOpusList = YES;
            editViewController.modalPresentationStyle = UIModalPresentationFullScreen;
            [viewController presentViewController:editViewController animated:NO completion:nil];
        });
    };
    
//    [ZLPhotoConfiguration default].previewVideoBlock = ^(AVPlayerItem * avPlayItem, UIViewController * viewController) {
//
//        AVAsset *asset = avPlayItem.asset;
//        if (asset != nil) {
//            AVURLAsset *urlAsset = (AVURLAsset *)asset;
//
//        }
//    };

    [sheet showPhotoLibraryWithSender:self];
}

- (void)setAuthStatusWithMessage:(NSString *)message{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [alertController dismissViewControllerAnimated:YES completion:nil];
        // 去设置相册权限
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication]canOpenURL:url]) {
            [[UIApplication sharedApplication]openURL:url options:@{} completionHandler:nil];
        }
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [alertController dismissViewControllerAnimated:YES completion:nil];
    }];
    [confirmAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
    [cancelAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
    //往alertViewController上添加alertAction
    [alertController addAction:cancelAction];
    [alertController addAction:confirmAction];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (scrollView.contentOffset.y <= 0) {
        self.refreshView.frame = CGRectMake(0,scrollView.contentOffset.y,kScreenW,-(scrollView.contentOffset.y * 2) + 120);
        self.refreshView.hidden = NO;
    }else{
        self.refreshView.hidden = YES;
    }
}


@end
